﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Base.Schema
{
    public class IdItemCollection<T> : ICollection<T> where T : IdentifiedItem
    {
        public IdItemCollection(SchemaItem owner)
        {
            _owner = owner;
        }

        private SchemaItem _owner;

        protected List<T> _items = new List<T>();

        // Collection stuff ////
        public void Add(T item)
        {
            item.Parent = (SchemaItem)_owner;
            _items.Add(item);
        }

        public void Clear()
        {
            _items.Clear();
        }

        public void CopyTo(T[] array, int arrayIndex)
        {
            _items.CopyTo(array, arrayIndex);
        }

        public bool Remove(T item)
        {
            return _items.Remove(item);
        }

        public int Count
        {
            get
            {
                return _items.Count;
            }
        }

        public bool IsReadOnly
        {
            get
            {
                return false;
            }
        }

        public bool Contains(T item)
        {
            return _items.Contains(item);
        }

        public IEnumerator<T> GetEnumerator()
        {
            return _items.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return _items.GetEnumerator();
        }

        // By GUID
        public virtual T this[Guid64 id]
        {
            get
            {
                foreach (T item in _items)
                {
                    if (item.Id == id)
                    {
                        return item;
                    }
                }

                throw new KeyNotFoundException(String.Format("No {0} with ID {1} found.", typeof(T).Name, id));
            }
            set
            {
                T item = this[id];
                item = value;
            }
        }

        // By name
        public virtual T this[string name]
        {
            get
            {
                foreach (T item in _items)
                {
                    if (item.Name == name)
                    {
                        return item;
                    }
                }

                throw new KeyNotFoundException(String.Format("No {0} with name '{1}' found.", typeof(T).Name, name));
            }
        }

    }
}
